<?php


namespace app\system\service;

class AgentService
{
	public static function getlist($options)
	{
		$where = [];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["id", "=", $options["id"]];
		}
		if (isset($options["account"]) && $options["account"] != "") {
			$where[] = ["account", "=", $options["account"]];
		}
		if (isset($options["qq"]) && $options["qq"] != "") {
			$where[] = ["qq", "=", $options["qq"]];
		}
		if (isset($options["level"]) && $options["level"] != "") {
			$where[] = ["level", "=", $options["level"]];
		}
		if (isset($options["superior_id"]) && $options["superior_id"]) {
			$where[] = ["superior_id", "=", $options["superior_id"]];
		}
		if (isset($options["name"]) && $options["name"] != "") {
			$where[] = ["name", "like", "%" . $options["name"] . "%"];
		}
		$list = \think\Db::name("app_agent")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_agent")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$data[] = self::get_array_info($item);
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function get_array_info($item)
	{
		$bindings = \think\Db::name("app_agent_binding")->where(["agent_id" => $item["id"]])->select();
		$item["binding_appids"] = [];
		foreach ($bindings as $binding) {
			$item["binding_appids"][] = $binding["appid"];
		}
		$item["binding_app_list"] = \think\Db::name("app")->whereIn("id", $item["binding_appids"])->field("id,name,type,avatar")->select();
		$item["superior_info"] = \think\Db::name("app_agent")->where(["id" => $item["superior_id"]])->field("id,name,qq,level,superior_id")->find() ?? [];
		$item["statistics"] = ["subordinate_count" => \think\Db::name("app_agent")->where(["superior_id" => $item["id"]])->count(), "card_count" => ["card" => \think\Db::name("app_card_user")->where(["agent_id" => $item["id"]])->count(), "member" => \think\Db::name("app_member_card")->where(["agent_id" => $item["id"]])->count(), "auth" => \think\Db::name("app_auth_card")->where(["agent_id" => $item["id"]])->count()]];
		return $item;
	}
	public static function getinfo($options)
	{
		$item = \think\Db::name("app_agent")->where(["id" => $options["id"]])->find();
		if (empty($item)) {
			return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
		}
		return ["code" => \app\system\model\Code::success, "data" => self::get_array_info($item)];
	}
	public static function add($options)
	{
		\think\Db::startTrans();
		try {
			$isSystemAuthUnpaid = isSystemAuthUnpaid();
			if ($isSystemAuthUnpaid && \think\Db::name("app_agent")->count() >= \app\common\model\FreeQuota::AgentQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,最多只能拥有" . \app\common\model\FreeQuota::AgentQuota . "个代理账号" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			if ($isSystemAuthUnpaid && \think\Db::name("app_agent")->where([["level", "=", 1]])->count() >= \app\common\model\FreeQuota::AgentLevenOneQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,一个应用最多只能拥有" . \app\common\model\FreeQuota::AgentLevenOneQuota . "个一级代理账号" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			$account = \think\Db::name("app_agent")->where("account", $options["account"])->find();
			if (!empty($account)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "用户名不可用"];
			}
			$password = GeneratePassword($options["password"]);
			$id = \think\Db::name("app_agent")->insertGetId(["create_time" => time(), "update_time" => time(), "name" => $options["name"], "account" => $options["account"], "password" => $password, "qq" => $options["qq"], "disable" => $options["disable"], "add_subordinate_authority" => $options["add_subordinate_authority"], "divide_subordinate_add_subordinate_authority" => $options["divide_subordinate_add_subordinate_authority"]]);
			if ($isSystemAuthUnpaid && \think\Db::name("app_agent_binding")->where(["agent_id" => $id])->count() >= \app\common\model\FreeQuota::AgentBindingAppQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,一个代理最多只能授权" . \app\common\model\FreeQuota::AgentBindingAppQuota . "个应用" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			\think\Db::name("app_agent_binding")->where(["agent_id" => $id])->delete();
			$data = [];
			$options["binding_appids"] = empty($options["binding_appids"]) ? [] : $options["binding_appids"];
			foreach ($options["binding_appids"] as $app_id) {
				$data[] = ["agent_id" => $id, "appid" => $app_id, "time" => time()];
			}
			\think\Db::name("app_agent_binding")->insertAll($data);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function edit($options)
	{
		\think\Db::startTrans();
		try {
			$item = \think\Db::name("app_agent")->where(["id" => $options["id"]])->find();
			if (empty($item)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			$data = ["update_time" => time(), "name" => $options["name"], "qq" => $options["qq"], "disable" => $options["disable"], "add_subordinate_authority" => $options["add_subordinate_authority"], "divide_subordinate_add_subordinate_authority" => $options["divide_subordinate_add_subordinate_authority"]];
			if (!empty($options["new_password"])) {
				$password = GeneratePassword($options["new_password"]);
				$data["password"] = $password;
			}
			\think\Db::name("app_agent")->where("id", $item["id"])->update($data);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function del($options)
	{
		\think\Db::startTrans();
		try {
			$row = \think\Db::name("app_agent")->where(["id" => $options["id"]])->find();
			if (empty($row)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			if (empty($options["mode"])) {
				$subs = \think\Db::name("app_agent")->where(["superior_id" => $options["id"]])->find();
				if ($subs) {
					return ["code" => \app\system\model\Code::fail, "msg" => "该代理存在子级代理无法删除"];
				}
				$ids[] = $row["id"];
			} else {
				if ($options["mode"] === "del_whole") {
					$ids = \app\agent\service\AgentService::get_subordinate_ids($row);
					$ids[] = $row["id"];
				}
			}
			\think\Db::name("app_agent")->whereIn("id", $ids)->delete();
			\think\Db::name("app_agent_binding")->whereIn("agent_id", $ids)->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功删除" . count($ids) . "个代理"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function revise_money($options)
	{
		\think\Db::startTrans();
		try {
			$agent = \think\Db::name("app_agent")->where(["id" => $options["id"]])->find();
			if (empty($agent)) {
				return json(["code" => -1, "msg" => "id不存在"]);
			}
			\app\common\AppAgent::money($agent, $options["number"], $options["type"], "后台操作,备注:" . $options["remarks"]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function get_recharge_cardlist($options)
	{
		$where = [];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["id", "=", $options["id"]];
		}
		if (isset($options["type"]) && $options["type"] != "") {
			$where[] = ["type", "=", $options["type"]];
		}
		if (isset($options["status"]) && $options["status"] != "") {
			$where[] = ["status", "=", $options["status"]];
		}
		if (isset($options["useuid"]) && $options["useuid"] != "") {
			$where[] = ["useuid", "=", $options["useuid"]];
		}
		if (isset($options["card"]) && $options["card"] != "") {
			$where[] = ["card", "like", "%" . $options["card"] . "%"];
		}
		$list = \think\Db::name("app_agent_recharge_card")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_agent_recharge_card")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$data[] = $item;
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function add_recharge_card($options)
	{
		if (\app\common\server\ConfigServer::get("system", \app\common\model\DefaultConfig::SystemTestDemoField, false) && $options["num"] > 2) {
			return ["code" => \app\system\model\Code::fail, "msg" => "当前站点为演示站点,一次最多只能生成2个" . \app\common\model\DefaultConfig::SystemTestDemoTipsSuffixText];
		}
		\think\Db::startTrans();
		try {
			$list = [];
			$head = empty($options["head"]) ? "" : $options["head"];
			$foot = empty($options["foot"]) ? "" : $options["foot"];
			for ($i = 0; $i < $options["num"]; $i++) {
				if (empty($options["body"])) {
					$body = md5(uniqid());
				}
				$card = $head . $body . $foot;
				$list[] = $card;
				\think\Db::name("app_agent_recharge_card")->insert(["type" => $options["type"], "value" => $options["value"], "addtime" => time(), "card" => $card, "give" => $options["give"] ?? 0]);
			}
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "data" => ["list" => $list, "string" => implode("\n", $list)], "msg" => "生成成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function del_recharge_card($options)
	{
		\think\Db::startTrans();
		try {
			$new = \think\Db::name("app_agent_recharge_card")->where(["id" => $options["id"]])->find();
			if (empty($new)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_agent_recharge_card")->where(["id" => $options["id"]])->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function get_app_binding_list($options)
	{
		$where = [];
		$where[] = ["binding.appid", "=", $options["appid"]];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["binding.agent_id", "=", $options["agent_id"]];
		}
		if (isset($options["superior_id"]) && $options["superior_id"] != "") {
			$where[] = ["binding.superior_id", "=", $options["superior_id"]];
		}
		if (isset($options["level"]) && $options["level"] != "") {
			$where[] = ["binding.level", "=", $options["level"]];
		}
		if (isset($options["qq"]) && $options["qq"] != "") {
			$where[] = ["binding.qq", "=", $options["qq"]];
		}
		$list = \think\Db::name("app_agent_binding")->alias("binding")->join("app_agent agent", "agent.id=binding.agent_id")->group("agent.id")->where($where)->field("binding.*")->order(["binding.id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_agent_binding")->alias("binding")->join("app_agent agent", "agent.id=binding.agent_id")->group("agent.id")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
		foreach ($list as $item) {
			$data[] = self::get_app_binding_array_info($item, $app);
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function get_app_binding_array_info($item, $app)
	{
		$agent = \think\Db::name("app_agent")->where(["id" => $item["agent_id"]])->find();
		$item["authority_config"] = \app\agent\service\AgentService::get_agent_authority_config($app, $agent, true);
		$item["agent_info"] = self::get_array_info($agent);
		$item["superior_agent_info"] = empty($item["superior_id"]) ? [] : self::get_array_info(\think\Db::name("app_agent")->where(["id" => $item["superior_id"]])->find());
		return $item;
	}
	public static function get_app_binding_info($options)
	{
		$item = \think\Db::name("app_agent_binding")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
		if (empty($item)) {
			return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
		}
		$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
		return ["code" => \app\system\model\Code::success, "data" => self::get_app_binding_array_info($item, $app)];
	}
	public static function add_app_binding($options)
	{
		\think\Db::startTrans();
		try {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "appid不存在"];
			}
			$binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $options["id"], "appid" => $options["appid"]])->find();
			if (!empty($binding)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "该应用已绑定"];
			}
			$isSystemAuthUnpaid = isSystemAuthUnpaid();
			if ($isSystemAuthUnpaid && \think\Db::name("app_agent_binding")->where(["agent_id" => $options["id"]])->count() >= \app\common\model\FreeQuota::AgentBindingAppQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,一个代理最多只能授权" . \app\common\model\FreeQuota::AgentBindingAppQuota . "个应用" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			\think\Db::name("app_agent_binding")->insert(["appid" => $options["appid"], "agent_id" => $options["id"], "time" => time()]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function edit_app_agent_binding($options)
	{
		\think\Db::startTrans();
		try {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "appid不存在"];
			}
			$binding = \think\Db::name("app_agent_binding")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
			if (empty($binding)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_agent_binding")->where(["id" => $options["id"]])->update(["authority_config" => json_encode($options["authority_config"])]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function del_app_binding($options)
	{
		\think\Db::startTrans();
		try {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "appid不存在"];
			}
			$binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $options["id"], "appid" => $options["appid"]])->find();
			if (empty($binding)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "未绑定该应用无需删除"];
			}
			$ids = \app\agent\service\AgentService::get_subordinate_ids(\think\Db::name("app_agent")->where(["id" => $binding["agent_id"]])->find());
			$ids[] = $binding["id"];
			\think\Db::name("app_agent_binding")->whereIn("id", $ids)->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function get_binding_app_data($options)
	{
		$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
		if (empty($app)) {
			return ["code" => \app\system\model\Code::fail, "msg" => "appid不存在"];
		}
		$binding = \think\Db::name("app_agent_binding")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
		if (empty($binding)) {
			return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
		}
		$result = \app\agent\service\AgentService::get_app_data(array_merge($options, ["appid" => $app["id"], "id" => $binding["agent_id"]]));
		return $result;
	}
	public static function subordinate_move($options)
	{
		\think\Db::startTrans();
		try {
			if ($options["id"] == $options["oid"]) {
				return ["code" => \app\system\model\Code::fail, "msg" => "无法迁移到自己"];
			}
			$row = \think\Db::name("app_agent")->where(["id" => $options["id"]])->find();
			if (empty($row)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "迁移对象id不存在"];
			}
			$new = \think\Db::name("app_agent")->where(["id" => $options["oid"]])->find();
			if (empty($new)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "迁移目标id不存在"];
			}
			if ($row["level"] != $new["level"]) {
				return ["code" => \app\system\model\Code::fail, "msg" => "仅支持迁移至同级代理下(迁移对象等级:" . $row["level"] . ",迁移目标等级:" . $new["level"] . ")"];
			}
			\think\Db::name("app_agent")->where("superior_id", $row["id"])->update(["superior_id" => $new["id"]]);
			\think\Db::name("app_agent_binding")->where("superior_id", $row["id"])->update(["superior_id" => $new["id"]]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "迁移完成"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function binding_app_card_disable($options)
	{
		\think\Db::startTrans();
		try {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "appid不存在"];
			}
			$binding = \think\Db::name("app_agent_binding")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
			if (empty($binding)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_agent_binding")->where(["id" => $binding["id"]])->update(["card_disable" => !$binding["card_disable"]]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "设置成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
}